package com.it.gmall.item.service;

import com.alibaba.fastjson.JSONObject;
import com.it.gmall.list.client.ListFeignClient;
import com.it.gmall.model.product.BaseCategoryView;
import com.it.gmall.model.product.SkuInfo;
import com.it.gmall.model.product.SpuSaleAttr;
import com.it.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class ItemApiServiceImpl implements ItemApiService {
    @Autowired
    private ProductFeignClient productFeignClient;

    // 注入线程池
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ListFeignClient listFeignClient;

    @Override
    public Map getItem(long skuId) {
        Map resultMap = new HashMap<>();

        // 获取商品库存信息
        CompletableFuture<SkuInfo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
            resultMap.put("skuInfo",skuInfo);
            return skuInfo;
        }, threadPoolExecutor);

        // 获取商品的实时价格
        CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
            BigDecimal price = productFeignClient.getSkuPrice(skuId);
            resultMap.put("price", price);
        }, threadPoolExecutor);

        // 添加商品的评分 多任务无需等待
        CompletableFuture.runAsync(()->{
            listFeignClient.incrHotScore(skuId,1);
        },threadPoolExecutor);

        CompletableFuture<Void> categoryViewCompletableFuture = skuInfoCompletableFuture.thenAccept((skuInfo) -> {
            // 获取三级分类
            BaseCategoryView baseCategoryView = productFeignClient.getBaseCategoryView(skuInfo.getCategory3Id());
            resultMap.put("categoryView", baseCategoryView);
        });

        CompletableFuture<Void> spuSaleAttrListCompletableFuture = skuInfoCompletableFuture.thenAccept((skuInfo -> {
            // 获取销售属性+是否选中
            List<SpuSaleAttr> spuSaleAttrListCheckBySku = productFeignClient.getSpuSaleAttrListCheckBySku(skuId, skuInfo.getSpuId());
            resultMap.put("spuSaleAttrList", spuSaleAttrListCheckBySku);
        }));

        CompletableFuture<Void> valuesSkuJsonCompletableFuture = skuInfoCompletableFuture.thenAccept((skuInfo -> {
            // 获取组合+对应的skuId
            Map skuValueIdsMap = productFeignClient.getSkuValueIdsMap(skuInfo.getSpuId());
            resultMap.put("valuesSkuJson", JSONObject.toJSONString(skuValueIdsMap));
        }));

        // 多任务组合
        CompletableFuture.allOf(priceCompletableFuture,categoryViewCompletableFuture,spuSaleAttrListCompletableFuture,valuesSkuJsonCompletableFuture).join();

        // 返回数据
        return resultMap;
    }
}
